package de.tum.wi.som.prio.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import de.tum.wi.som.Node;
import de.tum.wi.som.Project;
import de.tum.wi.som.prio.PriorityRule;
import de.tum.wi.som.util.PrioUtil;

/**
 * Prioritize by node with longest duration
 * @author enricopollok
 *
 */
public class MaximumOperationFirst implements PriorityRule{

    @Override
    public void prioritize(Project project) {
    	 project.calcProjectGraph();
         List<Node> remainingNodes = new ArrayList<Node>();
         remainingNodes.addAll(Arrays.asList(project.getNodes()));
         List<Node> scheduledNodes = new ArrayList<Node>();
         List<Node> accessibleNodes;
         while (!remainingNodes.isEmpty()) {
             accessibleNodes = PrioUtil.determineAccesibleNodes(scheduledNodes, project.getSource(), remainingNodes);
             if (accessibleNodes.size() == 0) {
            	 System.err.println("No accessible nodes found in LastComeFirstServe");
            	 return;
             }

             // prioritize accesible nodes

             Collections.sort(accessibleNodes, new CustomComparator());
             remainingNodes.removeAll(accessibleNodes);
             scheduledNodes.addAll(accessibleNodes);
         }
         project.setNodes(scheduledNodes.toArray(new Node[scheduledNodes.size()]));
    }

    class CustomComparator implements Comparator<Node>{

        @Override
        public int compare(Node o1, Node o2) {
            if (o1.getD() == o2.getD())
                return 0;
            else{
                return o1.getD() > o2.getD() ? -1 : 1;
            }
        }

    }
    
    @Override
	public String toString(){
		return "MaximumOperationFirst";
	}

}
